/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message } from 'antd';
import { getTwoOrderList, getChartList } from '@/services/delivery';
import moment from 'moment';

const dataFormat = 'YYYY-MM-DD';

const filter = (data, type)=> {
    let dataSource = [], yestory = moment(new Date()).add(-1, 'day').format(dataFormat), last_yestory = moment(new Date()).add(-2, 'day').format(dataFormat);
    let chartList = [];
    data.list.length > 0 && data.list.map(item=> {
        if (item.arrived_ymd == yestory) {
            dataSource.push({
                ...item,
                top3: data.top_list[yestory],
                date: '昨天'
            })
        }
        if (item.arrived_ymd == last_yestory) {
            dataSource.push({
                ...item,
                top3: data.top_list[last_yestory],
                date: '前天'
            })
        }
        chartList.push({
            value: type != 'company_muns' ? parseFloat(item[type]) : parseFloat(item['receipts_muns']) - parseFloat(item['earnings_muns']),
            year: item['arrived_ymd']
        })
    })
    return {
        chartList,
        dataSource
    }
}

export default {
    namespace: 'delivery',
    state: {
        orderList: {},
        chartList: [],
    },

    effects: {
        *getChartList({ payload }, { call, put,select }) {
            const {allData} = yield select(_=>_.delivery)
            if (allData) {
                const d = filter(allData, payload.type);
                yield put({
                    type: 'save',
                    payload: {
                        allData: allData,
                        chartList: d.chartList,
                        orderList: {
                            list: d.dataSource
                        }
                    },
                });
                return;
            }
            let { code, data } = yield call(getChartList);
            if (code == 0) {
                const d = filter(data, payload.type);
                yield put({
                    type: 'save',
                    payload: {
                        allData: data,
                        chartList: d.chartList,
                        orderList: {
                            list: d.dataSource
                        }
                    },
                });
            }
        },
    },

    reducers: {
        save(state, { payload }) {
            return {
                ...state,
                ...payload,
            };
        },
    },
};
